<template>
  <div class="auth-page">
    <div class="container page">
      <div class="row">

        <div class="col-md-6 offset-md-3 col-xs-12">
          <h1 class="text-xs-center"> {{ title }} </h1>
          <p class="text-xs-center">
            <!-- <a href="">Have an account?</a> -->
            <nuxt-link :to="isLogin ? '/register':'/login'">
              {{ isLogin ? 'Need an account' : 'Have an account?' }}
            </nuxt-link>
          </p>

          <ul class="error-messages">
            <template v-for="(error, key) in errors">
              <li v-for="(msg, i) in error"
                  :key="i">
                {{ key }} {{ msg }}
              </li>
            </template>
          </ul>

          <form @submit.prevent="submit">
            <fieldset class="form-group"
                      v-if="!isLogin">
              <input class="form-control form-control-lg"
                     required
                     type="text"
                     v-model="user.username"
                     placeholder="Your Name">
            </fieldset>
            <fieldset class="form-group">
              <input class="form-control form-control-lg"
                     required
                     type="email"
                     v-model="user.email"
                     placeholder="Email">
            </fieldset>
            <fieldset class="form-group">
              <input class="form-control form-control-lg"
                     required
                     type="password"
                     minlength="8"
                     v-model="user.password"
                     placeholder="Password">
            </fieldset>
            <button class="btn btn-lg btn-primary pull-xs-right">
              {{ title }}
            </button>
          </form>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import { login, register } from '@/api/user'
const Cookie = process.client ? require('js-cookie') : undefined

export default {
  middleware: 'noAuthenticate',
  name: 'Login',
  head() {
    return {
      title: this.isLogin ? 'Login' : 'Register',
      meta: [
        {
          hid: this.isLogin ? 'login' : 'register',
          name: this.isLogin ? 'login' : 'register',
          content: this.isLogin ? 'login realworld' : 'register user'
        }
      ]
    }
  },
  data() {
    return {
      user: {
        email: '',
        username: '',
        password: ''
      },
      errors: {}
    }
  },
  methods: {
    async submit() {
      // 是否登录
      console.log('submit')
      // 通过 try catch 捕获错误
      try {
        if (this.isLogin) {
          let { data } = await this.login()
          // 本地存储登录状态
          this.$store.commit('cacheUser', data.user)
          // 登录状态持久化，存储到 cookie 中，并在服务端渲染的时候拿取 cookie 中的状态初始化到 state 中
          // Cookie.set('user', data.user) 废弃

          // TODO: 优化获取用户信息的流程，通过存储用户token，并通过 token 获取用户实时信息（已完成）
          Cookie.set('token', data.user.token)
          this.$router.push('/')
        } else {
          let { data } = await this.register()
        }
      } catch (error) {
        this.errors = error.response.data.errors
      }
    },
    async login() {
      return login({
        user: this.user
      })
    },
    async register() {
      return register({
        user: this.user
      })
    }
  },
  computed: {
    isLogin() {
      return this.$route.name === 'login'
    },
    title() {
      return this.isLogin ? 'Sign in' : 'Sign up'
    }
  }
}
</script>

<style>
</style>